package www.dbconfig;

import com.zaxxer.hikari.HikariDataSource;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.sql.core.ClasspathLoader;
import org.beetl.sql.core.Interceptor;
import org.beetl.sql.core.UnderlinedNameConversion;
import org.beetl.sql.core.db.MySqlStyle;
import org.beetl.sql.ext.DebugInterceptor;
import org.beetl.sql.ext.spring4.BeetlSqlDataSource;
import org.beetl.sql.ext.spring4.SqlManagerFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @program: Sky
 * @description: beetlsql配置
 * @author: Mr.Yan
 * @create: 2019-03-07 09:54
 **/
@Configuration
@Profile(value = "db")
public class beetlsqlConfig {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //配置文件
    @Bean(initMethod = "init", name = "beetlConfig")
    public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {

        BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
        //打成jar 包不能访问 修改下面
        ClasspathResourceLoader classpathResourceLoader = new ClasspathResourceLoader();
        beetlGroupUtilConfiguration.setResourceLoader(classpathResourceLoader);
        //读取配置文件信息
        return beetlGroupUtilConfiguration;

    }

    //配置数据库
    @Bean(name = "datasource")
    public DataSource getDataSource(Environment env) {
        logger.warn("————————————初始化数据库连接...");
        HikariDataSource ds = null;
        try {
            String driverClass = env.getProperty("spring.datasource.driver-class-name");
            String url = env.getProperty("spring.datasource.mysql.url");
            String userName = env.getProperty("spring.datasource.mysql.username");
            String passWord = env.getProperty("spring.datasource.mysql.password");
            logger.warn("");
            logger.warn("数据库连接池: " + driverClass);
            logger.warn("数据库  地址: " + url);
            logger.warn("数据库用户名: " + userName);
            logger.warn("数据库  密码: " + passWord);
            logger.warn("");
            // 测试数据库连接
            Connection connection = getConnection(env);

            ds = new HikariDataSource();
            ds.setDriverClassName(driverClass);
            ds.setJdbcUrl(url);
            ds.setUsername(userName);
            ds.setPassword(passWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ds;
    }

   /* //配置数据库
    @Bean(name = "datasourceOther")
    public DataSource getDataSourceOther(Environment env) {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(env.getProperty("spring.datasource-other.mysql.url"));
        ds.setUsername(env.getProperty("spring.datasource-other.mysql.username"));
        ds.setPassword(env.getProperty("spring.datasource-other.mysql.password"));
        ds.setDriverClassName(env.getProperty("spring.datasource-other.driver-class-name"));
        return ds;
    }*/

    @Bean(name = "sqlManagerFactoryBean")
    @Primary
    public SqlManagerFactoryBean getSqlManagerFactoryBean(
            @Qualifier("datasource") DataSource datasource,
            //@Qualifier("datasourceOther") DataSource datasourceOther,
            Environment env) {
        String sqlLoader = env.getProperty("beetlsql.sqlLoader");

        SqlManagerFactoryBean factory = new SqlManagerFactoryBean();
        BeetlSqlDataSource source = new BeetlSqlDataSource();
        source.setMasterSource(datasource);
        //配置多数据库连接
        //source.setSlaves(new DataSource[]{datasourceOther});

        factory.setCs(source);
        factory.setDbStyle(new MySqlStyle());
        factory.setInterceptors(new Interceptor[]{new DebugInterceptor()});
        factory.setNc(new UnderlinedNameConversion());//开启自定义映射
        factory.setSqlLoader(new ClasspathLoader(sqlLoader));//sql文件路径
        return factory;
    }

    //开启事务
  /* @Bean(name = "txManager")
    public DataSourceTransactionManager getDataSourceTransactionManager(
            @Qualifier("datasource") DataSource datasource) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(datasource);
        return dsm;
    }*/

  private Connection getConnection(Environment env){
      try{
          logger.warn("————————————测试数据库连接...");
          logger.warn("...");
          String driverClass = env.getProperty("spring.datasource.driver-class-name");
          String url = env.getProperty("spring.datasource.mysql.url");
          String userName = env.getProperty("spring.datasource.mysql.username");
          String passWord = env.getProperty("spring.datasource.mysql.password");
          Class.forName(driverClass);
          Connection conn= DriverManager.getConnection(url,userName,passWord);//获取连接对象
          logger.warn("...");
          logger.warn("————————————数据库连接成功");
          logger.warn("");
          return conn;
      }catch(ClassNotFoundException e){
          logger.warn("...");
          logger.warn("————————————没有找到连接数据库驱动类");
          logger.warn("");
          e.printStackTrace();
      }catch(SQLException e){
          logger.warn("...");
          logger.warn("————————————数据库连接失败");
          logger.warn("");
          e.printStackTrace();
      }
      return null;
  }
}
